/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-10-26 20:00:00
 * @LastEditTime: 2022-10-28 18:56:06
 */
import { createContext, useReducer, useEffect, useContext } from 'react';
import { message, Modal } from 'antd';
import { addRepo, fetchRepoByPage, deleteRepo, editRepo } from '@/api/archivesType';
import {
  ADD_LIB_LIST,
  DELETE_LIB_LIST,
  EDIT_LIB_LIST,
  SET_SELECT_KEY,
  SET_LIB_LIST
} from '../constants';
import { LIBManageReducer } from '../reducers/LIBManageReducer';
const initialState = {
  libraryList: [],
  selectItems: []
};
const LIBManageContext = createContext();
const LIBManageContextProvider = (props) => {
  const [state, dispatch] = useReducer(LIBManageReducer, initialState);
  const actions = {
    setSelectKey(data) {
      dispatch({ type: SET_SELECT_KEY, data });
    },
    /**
     * @description: 获取库列表方法
     * @param {IExportListParams} params 参数
     * @return {Promise}
     */
    getLibraryList(params) {
      return new Promise((resolve, reject) => {
        fetchRepoByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_LIB_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /* 增加库列表 */
    addBoxListData(data) {
      addRepo(data).then((res) => {
        const { data } = res;
        console.log(data);
        dispatch({ type: ADD_LIB_LIST, data });
      });
    },
    /* 删除库列表 */
    delLIBManageFunc(id, title = '确认删除此盒规格？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteRepo(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DELETE_LIB_LIST, ids: data });
          });
          // dispatch({ type: DELETE_LIB_LIST, ids: id });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },
    /* 编辑库列表 */
    editLIBManage(query) {
      return new Promise((resolve, reject) => {
        editRepo(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_LIB_LIST, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
      // console.log(query);
      // dispatch({ type: EDIT_LIB_LIST, data: query, id: query.id });
    }
  };
  useEffect(() => {}, []);
  return (
    <LIBManageContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </LIBManageContext.Provider>
  );
};
export const useLIBManageContext = () => {
  return useContext(LIBManageContext);
};
export { LIBManageContext, LIBManageContextProvider };
